<template>
  <div>
    <van-row type="flex" justify="center">
      <van-image :src="require('@/assets/images/logo.png')"></van-image>
    </van-row>
    <van-cell-group inset>
      <!-- 输入账号（用户名） -->
      <van-field label="账号" placeholder="请输入账号" v-model="loginForm.name"></van-field>
      <!-- 输入密码 -->
      <van-field label="密码" placeholder="请输入密码" type="password" v-model="loginForm.password"></van-field>

      <!-- 登录按钮 -->
      <van-button type="primary" size="large" @click="onClickLogin">登录</van-button>

      <!-- 注册按钮 -->
      <van-button class="goto" type="info" size="large" @click="onClickRegister">如果没有账号，请立即注册</van-button>
    </van-cell-group>
  </div>
</template>

<script>
  import {
    loginAPI
  } from "@/api/user.js" //导入登录接口
  import * as Auth from "@/utils/auth.js" //导入本地存储方法
  export default {
    name: "login",
    data() {
      return {
        loginForm: {
          name: "dingding", //用户名，仅仅测试方便
          password: "123456",
        }
      }
    },

    //生命周期钩子函数，在组件DOM元素加载好了后被调用
    mounted() {
      //初始赋值 ，从本地存储中获取用户名
      this.loginForm.name = Auth.getUserLocal().name;
    },

    methods: {
      onClickLogin() {
        //this.$toast("登录，还没实现")
        if (this.loginForm.name === "" || this.loginForm.password === "") {
          this.$toast("账号或密码不能为空");
          return;
        }

        let params = this.loginForm;
        loginAPI(params).then(result => {
          console.log(result);
          this.$toast({
            message: "登录成功！",
            duration: 1000
          });
          //把返回的 user 、token 在本地保存
          Auth.setTokenLocal(result.data.token); //保存Token
          Auth.setUserLocal(result.data.user); //保存用户数据

          //实现路由跳转页面 看看当前路由是否指定有重定向地址 否则跳转 user
          let toPath = this.$route.params.redirect || "user";
          //延时1秒后路由跳转
          setTimeout(() => {
            this.$router.replace({
              path: toPath
            });
          }, 1000);
        }).catch((error) => {
          console.log(error);
        });
      },

      onClickRegister() {
        //路由跳转到用户注册页面
        // this.$toast("注册，还没实现！");
        this.$router.push({
          name: "register"
        });
      }
    },
  };
</script>

<style lang="less" scoped>
.login-container {
  padding: 40px 20px;
  background-color: #f9f9f9;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.van-image {
  margin-bottom: 30px;
}

.van-field {
  margin-bottom: 15px;
  border: 1px solid #ddd;
  border-radius: 5px;
  background-color: #fff;
}

.van-field__label {
  font-size: 16px;
  color: #333;
}

.van-field__control {
  font-size: 16px;
}

.van-button {
  margin-top: 20px;
  border-radius: 5px;
  font-size: 18px;
}

.goto {
  display: block;
  margin-top: 25px;
  text-align: center;
  color: #666;
  text-decoration: underline;
}
</style>